﻿@page "/Account/Manage/DeletePersonalData"

@using System.ComponentModel.DataAnnotations
@using Microsoft.AspNetCore.Identity
@using BlazorWeb_CSharp.Data

@inject UserManager<ApplicationUser> UserManager
@inject SignInManager<ApplicationUser> SignInManager
@inject IdentityUserAccessor UserAccessor
@inject IdentityRedirectManager RedirectManager
@inject ILogger<DeletePersonalData> Logger

<PageTitle>Delete Personal Data</PageTitle>

<StatusMessage Message="@message" />

<h3>Delete Personal Data</h3>

<FluentGrid>
    <FluentGridItem sm="6">
        <div class="alert alert-warning" role="alert">
            <p>
                <strong>Deleting this data will permanently remove your account, and this cannot be recovered.</strong>
            </p>
        </div>
        <EditForm Model="Input" FormName="delete-user" OnValidSubmit="OnValidSubmitAsync" method="post">
            <DataAnnotationsValidator />
            <FluentValidationSummary class="text-danger" role="alert" />
            @if (requirePassword)
            {
                <FluentTextField type="password" Name="Input.Password" @bind-Value="Input.Password" AutoComplete="new-password" Required="true" Placeholder="Please enter your password." Label="Password" Style="width: 100%" />
                <FluentValidationMessage For="() => Input.Password" class="text-danger" />
            }
            <FluentButton Type="ButtonType.Submit" Appearance="Appearance.Accent" Style="width: 100%;">Delete data and close my account</FluentButton>
        </EditForm>
    </FluentGridItem>
</FluentGrid>
@code {
    private string? message;
    private ApplicationUser user = default!;
    private bool requirePassword;

    [CascadingParameter]
    private HttpContext HttpContext { get; set; } = default!;

    [SupplyParameterFromForm]
    private InputModel Input { get; set; } = new();

    protected override async Task OnInitializedAsync()
    {
        Input ??= new();
        user = await UserAccessor.GetRequiredUserAsync(HttpContext);
        requirePassword = await UserManager.HasPasswordAsync(user);
    }

    private async Task OnValidSubmitAsync()
    {
        if (requirePassword && !await UserManager.CheckPasswordAsync(user, Input.Password))
        {
            message = "Error: Incorrect password.";
            return;
        }

        var result = await UserManager.DeleteAsync(user);
        if (!result.Succeeded)
        {
            throw new InvalidOperationException("Unexpected error occurred deleting user.");
        }

        await SignInManager.SignOutAsync();

        var userId = await UserManager.GetUserIdAsync(user);
        Logger.LogInformation("User with ID '{UserId}' deleted themselves.", userId);

        RedirectManager.RedirectToCurrentPage();
    }

    private sealed class InputModel
    {
        [DataType(DataType.Password)]
        public string Password { get; set; } = "";
    }
}
